package com.ybwh.springboot2.common.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

/**
 * 初始化全局 SpringApplication FullBeanNameGenerator，修复ConflictingBeanDefinitionException
 *
 * @author wangcong
 */
@Slf4j
public class FullBeanNameGeneratorConfigListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    private static final String BCCP_BEANNAME_GENERATOR = "bccp.beanNameGenerator";

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        SpringApplication springApplication = event.getSpringApplication();
        ConfigurableEnvironment environment = event.getEnvironment();
        String beanNameGeneratorClass = environment.getProperty(BCCP_BEANNAME_GENERATOR);

        if (StringUtils.isEmpty(beanNameGeneratorClass)) {
            return;
        }

        try {
            Class<?> beanNameClass = ClassUtils.forName(beanNameGeneratorClass, Thread.currentThread().getContextClassLoader());
            BeanNameGenerator beanNameGenerator = BeanUtils.instantiateClass(beanNameClass, BeanNameGenerator.class);
            springApplication.setBeanNameGenerator(beanNameGenerator);
            log.info("configing using beanNameGenerator '{}'", beanNameGenerator);
        } catch (ClassNotFoundException e) {
            //replace default log.warn("beanNameGenerator class '{}' not found , replace to default 'FullBeanNameGenerator'", e.getMessage());
            springApplication.setBeanNameGenerator(new FullBeanNameGenerator());
        }
    }


}
